import datetime

from sqlalchemy import insert, update
from sqlalchemy.exc import IntegrityError

from src.database.exception_mapper import exception_mapper
from src.database.models import Statistics
from src.database.repositories.base import SQLAlchemyRepo


class StatsRepoImpl(SQLAlchemyRepo):
    @exception_mapper
    async def add_or_update_stats(
        self,
        date: datetime.date,
        products_purchased: int,
        orders_created: int,
        users_registered: int,
        payments_payed: int,
    ) -> None:
        try:
            await self._session.execute(
                insert(Statistics).values(
                    date=date,
                    products_purchased=products_purchased,
                    orders_created=orders_created,
                    users_registered=users_registered,
                    payments_payed=payments_payed,
                )
            )
        except IntegrityError:
            await self._session.execute(
                update(Statistics)
                .where(Statistics.date == date)
                .values(
                    products_purchased=Statistics.products_purchased
                    + products_purchased,
                    orders_created=Statistics.orders_created + orders_created,
                    users_registered=Statistics.users_registered + users_registered,
                    payments_payed=Statistics.payments_payed + payments_payed,
                )
            )
